<template>
  <div class="all">
    <el-dialog
      v-model="centerDialogVisible"
      @close="onClose"
      :title="dialogTitle"
      width="30%"
      align-center
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="父类节点" prop="pid">
          <el-tree-select
            :placeholder="selectVal"
            v-if="treeDataStatus"
            :disabled="isDisabled"
            check-strictly
            :remote="true"
            v-model="ruleForm.pid"
            lazy
            :load="load"
            :props="props"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="ruleForm.name"

            autocomplete="off"
            placeholder="请输入分类名称"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="ruleForm.sort"
            :precision="2" 
            controls-position="right"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            autocomplete="off"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-divider />
        <div class="btn-all">
          <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { vCheckVal } from '@/directives/checkVal'
// import { bool } from 'vue-types'
import type Node from 'element-plus/es/components/tree/src/model/node'
import {
  getClassList,
  categoryLoadTreeData,
  getClassChildList,
  categoryAdd,
  categoryEdit,
  categoryLoadDictItem,
  categoryQueryById
} from '@/api/classDictionary/index'
import { classChildListTreeType, classListTreeType } from '../type'
const centerDialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const editInfo = ref<object>({})
const dialogTitle = ref('')
let isDisabled = ref(false)
let selectVal = ref('')
//渲染数据
const classListTreeData = ref<classListTreeType>({
  pid: 0,
  tableName: 'sys_category',
  text: 'name',
  code: 'id',
  pidField: 'pid',
  hasChildField: '',
  condition: ''
})
//渲染子级
const classChildListData = ref<classChildListTreeType>({
  tableName: 'sys_category',
  text: 'name',
  code: 'id',
  pidField: 'pid',
  hasChildField: '',
  condition: '',
  pid: 0
})
let getClassListFn = async () => {
  // console.log(classListTreeData.value, 'classListTreeData.value')
  return await categoryLoadTreeData(classListTreeData.value)
  // return await getClassList(classListData.value)
}
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请选择父类节点'))
  } else {
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入类型名称'))
  } else {
    callback()
  }
}
const ruleForm = reactive({
  pid: '',
  name: '',
  remark: '',
  sort: ''
})
const props = {
  label: 'title',
  children: 'children',
  isLeaf: 'isLeaf',
  value: 'key'
}
interface treeDataObj {
  id: number
  name: string
  isLeaf?: boolean
  children?: any
}
let treeDataStatus = ref(false)
let treeData = ref<treeDataObj[]>([])
//懒加载tree
const load = async (node: Node, resolve: (data: treeDataObj[]) => void) => {
  let timer: NodeJS.Timer | null = null
  clearTimeout(timer)
  // console.log(node.data.key, 'node', node)
  if (node.data.key) {
    classChildListData.value.pid = node.data.key
  }
  let { result } = await categoryLoadTreeData(classChildListData.value)
  if (node.level === 0) {
    return resolve(treeData.value)
  }
  // if (node.level > 2) return resolve([])

  timer = setTimeout(() => {
    node.data.children = result
    resolve(node.data.children)
  }, 400)
}

const rules = reactive<FormRules>({
  // value: [{ required: false, validator: validatePass, trigger: 'blur' }],
  name: [{ required: true, validator: validatePass2, trigger: 'blur' }]
})
//声明emit
const emit = defineEmits(['submit'])
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (dialogTitle.value == '新增') {
        let { code, message } = await categoryAdd(ruleForm)
        if (Number(code) == 200) {
          centerDialogVisible.value = false
          treeDataStatus.value = false
          emit('submit', true)
          ElMessage({
            message: message,
            type: 'success'
          })
        } else {
          ElMessage.error(message)
        }
      } else if (dialogTitle.value == '编辑') {
        // categoryEdit
        editInfo.value.name = ruleForm.name
        editInfo.value.remark = ruleForm.remark
        editInfo.value.sort = ruleForm.sort
        let { code, message } = await categoryEdit(editInfo.value)
        // console.log(code, message)
        if (Number(code) == 200) {
          centerDialogVisible.value = false
          treeDataStatus.value = false
          emit('submit', true)
          ElMessage({
            message: message,
            type: 'success'
          })
        } else {
          ElMessage.error(message)
        }
      } else {
        editInfo.value.pid = editInfo.value.id
        editInfo.value.id = ''
        editInfo.value.name = ruleForm.name
        editInfo.value.remark = ruleForm.remark
        editInfo.value.sort = ruleForm.sort
        let { code, message } = await categoryAdd(editInfo.value)
        if (Number(code) == 200) {
          centerDialogVisible.value = false
          treeDataStatus.value = false
          emit('submit', true)
          ElMessage({
            message: message,
            type: 'success'
          })
        } else {
          ElMessage.error(message)
        }
      }

      // console.log('submit!', ruleForm)
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false
  treeDataStatus.value = false
}
//添加
const dialogOnAdd = async (res: boolean) => {
  let { result } = await getClassListFn()
  treeData.value = result
  dialogTitle.value = '新增'
  selectVal.value = '请选择'
  centerDialogVisible.value = res
  isDisabled.value = false
  ruleForm.name = ''
  ruleForm.pid = ''
  ruleForm.remark = ''
  ruleForm.sort = ''
  treeDataStatus.value = true
}
//编辑
const dialogOnEdit = async (res: boolean, row: any) => {
  centerDialogVisible.value = res
  isDisabled.value = true
  treeDataStatus.value = true
  dialogTitle.value = '编辑'
  editInfo.value = row
  ruleForm.name = row.name
  ruleForm.remark = row.remark
  ruleForm.sort = row.sort
  ruleForm.pid = ''
  let { result } = await categoryLoadDictItem({ ids: editInfo.value.pid })
  selectVal.value = result[0] ? result[0] : '请选择'
}
//添加子分类
const dialogChildOnAdd = async (res: boolean, row: object) => {
  centerDialogVisible.value = res
  treeDataStatus.value = true
  isDisabled.value = true
  dialogTitle.value = '添加子分类'
  editInfo.value = row
  ruleForm.pid = ''
  ruleForm.name = ''
  ruleForm.remark = ''
  ruleForm.sort = ''
  // console.log(editInfo.value)
  let { result } = await categoryLoadDictItem({ ids: editInfo.value.id })
  // console.log(result, 'result')
  selectVal.value = result[0] ? result[0] : '请选择'
}
//关闭弹窗
const onClose = () => {
  centerDialogVisible.value = false
  isDisabled.value = false
  ruleFormRef.value?.resetFields()
}
defineExpose({
  dialogOnAdd,
  dialogOnEdit,
  dialogChildOnAdd
})
</script>

<style lang="less" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
// :deep(.demo-ruleForm .el-input) {
//   width: 400px;
// }

.btn-all {
  float: right;
  padding-bottom: 20px;
}
:deep(.el-select) {
  width: 100%;
}
</style>
